<script>
import { useVModel } from '@vueuse/core'
import { provide } from 'vue'

export default {
  name: 'XtxTabs',
  props: {
    modelValue: {
      type: [String, Number],
      default: ''
    }
  },
  setup (props, { emit }) {
    const activeName = useVModel(props, 'modelValue', emit)

    // 将当前激活的选项卡的名字传递给pannel
    provide('activeName', activeName)

    // 点击选项卡触发的方式
    const tabClick = (name, index) => {
      activeName.value = name

      // 触发自定义事件
      emit('tab-click', { name, index })
    }

    return { activeName, tabClick }
  },
  render () {
    // 获取默认插槽内容
    const pannels = this.$slots.default()

    // 动态pannel组件集合
    const dynamicPannels = []

    pannels.forEach((item) => {
      // 静态
      if (item.type.name === 'XtxTabsPannel') {
        dynamicPannels.push(item)
      } else {
        item.children.forEach((item) => {
          dynamicPannels.push(item)
        })
      }
    })

    /*
    1、tabs大容器
    2、选项卡的导航菜单结构
    3、内容容器
  */

    const nav = (
      <nav>
        {dynamicPannels.map((item, i) => {
          return (
            <a
              class={{ active: item.props.name === this.activeName }}
              href="javascript:;"
              onClick={() => this.tabClick(item.props.name, i)}
            >
              {item.props.label}
            </a>
          )
        })}
      </nav>
    )

    return <div class="xtx-tabs">{[nav, dynamicPannels]}</div>
  }
}
</script>

<style lang="less">
.xtx-tabs {
  background: #fff;
  > nav {
    height: 60px;
    line-height: 60px;
    display: flex;
    border-bottom: 1px solid #f5f5f5;
    > a {
      width: 110px;
      border-right: 1px solid #f5f5f5;
      text-align: center;
      font-size: 16px;
      &.active {
        border-top: 2px solid @xtxColor;
        height: 60px;
        background: #fff;
        line-height: 56px;
      }
    }
  }
}
</style>
